using Microsoft.SqlServer.Management.Sdk.Sfc;
using System;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
	internal class DefaultDatabaseObjectScriptHandler : ScriptHandler
	{
		private ScriptActions scriptType;

		private ScriptedObjectCollection objectsScripted = new ScriptedObjectCollection();

		public DefaultDatabaseObjectScriptHandler(ScriptActions scriptType) : this(scriptType, null)
		{
		}

		public DefaultDatabaseObjectScriptHandler(ScriptActions scriptType, ScriptHandler successor) : base(successor)
		{
			this.scriptType = scriptType;
		}

		protected override bool HandleScriptedEventCore(ObjectScriptedEventArgs e)
		{
			if (this.scriptType == ScriptActions.None || (this.scriptType & e.Action) == ScriptActions.None || e.ObjectInfo.Urn.Type == "DdlTrigger")
			{
				return false;
			}
			if (DefaultDatabaseObjectScriptHandler.IsSupportedObject(e.ObjectInfo.Urn))
			{
				this.objectsScripted.AddScriptFragment(e.ObjectInfo, e.Script, e.Action);
				return true;
			}
			return false;
		}

		protected override void ScriptCore(ScriptWriter scriptWriter)
		{
			this.objectsScripted.ScriptAll(scriptWriter);
		}

		private static bool IsSupportedObject(Urn item)
		{
			return DefaultDatabaseObjectScriptHandler.IsDatabaseScopedObject(item) && !ObjectsWithDependencies.CanDiscoverDependencies(item);
		}

		private static bool IsDatabaseScopedObject(Urn item)
		{
			do
			{
				item = item.Parent;
			}
			while (item != null && item.Type != "Database");
			return item != null;
		}
	}
}
